package ks.server.controllers.commands.admin.user;

import java.util.Collection;

import ks.framework.common.Message;
import ks.framework.communicator.Communicator;
import ks.framework.interfaces.IProcessMessage;
import ks.managers.user.User;
import ks.server.ipc.Listener;
import ks.server.persist.PersistentUserManager;
import ks.server.ServerContext;

import org.w3c.dom.Document;

/**
 * Process request to send status of player accounts on system.
 * 
 * @author Christopher Page
 */
public class UserListController implements IProcessMessage {

	/** Primary agent to whom we can communicate our messages. */
	Communicator com;
	
	public UserListController (Communicator com) {
		this.com = com;
	}
	
	/**
	 * Process the message
	 * 
	 * @param m The message to process.
	 * @return A boolean value.
	 */
	public boolean process(Message m) {
		PersistentUserManager um = ServerContext.getUserManager();
		
		// Verify that command originator is an admin
		if (um.getUser(m.getOriginator()) == null) {
			Listener.nack(m, 4, "Unable to get user list: what!? I don't even...");
			return true;
		}
		else if (!um.getUser(m.getOriginator()).isAdmin()) {
			Listener.nack(m, 4, "Unable to get user list: access denied.");
			return true;
		}
		
		// get usernames of online users
		Collection<String> onlineUsernames = com.getOnlineUsers();
		Collection<User> users = um.getUserList();
		
		StringBuilder sb = new StringBuilder("<request version='1.0' id='589a39591271844e3fbe32bbb9281ad9'>");
		sb.append("<users>");
		String online;
		for (User u : users) {
			if(onlineUsernames.contains(u.getName()))
				online = "true";
			else
				online = "false";
			
			sb.append("<allplayer name=\"" + u.getName() + "\" rating=\"" + u.getRating() + "\" icon=\"" + u.getIconName() + "\" online=\"" + online + "\" />");
		}
		sb.append("</users>");
		sb.append("</request>");
		
		// send request to command originator
		Document d = Message.construct(sb.toString());
		Message r = new Message(d);
		r.setRecipient(m.getOriginator());
		return com.distribute(r);
	}
}
